package ip.youtube;

import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;

import com.icesoft.faces.context.effects.JavascriptContext;

public class loginBean {

	private String name;
	private String password;
	private String userfail;
	
	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getUserfail() {
		return userfail;
	}

	public void setUserfail(String userfail) {
		this.userfail = userfail;
	}

	public void checkLogin(ActionEvent e){

		FacesContext context = FacesContext.getCurrentInstance();	
				
		UserDAO userdao = new UserDAO();
		User user = new User(); 
		
		user = userdao.getUserByName(name);
		
		
		if(user.getUsername() == null){
			userfail = "User do not exsits";
		}	
				
		if (password.equals(user.getPassword())) {
			// Valid login
			//*html5 WebStorage*
			JavascriptContext.addJavascriptCall(context, "window.sessionStorage.setItem('authorized','yes')");
			JavascriptContext.addJavascriptCall(context, "window.sessionStorage.setItem('User_id', '" + user.getUser_Id() + "')");
		} else {
	        // Invalid login
			//*html5 WebStorage*
			JavascriptContext.addJavascriptCall(context, "window.sessionStorage.setItem('authorized','no')");
			userfail = "wrong password";
		}
	}
	
	public void logout(){
		FacesContext context = FacesContext.getCurrentInstance();
		JavascriptContext.addJavascriptCall(context, " window.sessionStorage.removeItem('authorized')");
		JavascriptContext.addJavascriptCall(context, " window.sessionStorage.removeItem('User_id')");
	}
}
